package com.mccken.demo.io.netty.client;

import com.mccken.demo.io.netty.support.RpcFutureResponse;
import com.mccken.demo.io.netty.support.RpcResponse;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2022-04-30 20:50
 **/
@Slf4j
public class ClientHandler extends SimpleChannelInboundHandler<RpcResponse> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RpcResponse msg) throws Exception {
		log.info("接收到服务端的消息: requestId = " + msg.getRequestId());
		
		// 接收到服务无端的消息后，通知响应已经完成
		RpcFutureResponse rpcFutureResponse = RpcFutureResponse.getRpcFutureResponse(msg.getRequestId());
		if (null != rpcFutureResponse) {
			rpcFutureResponse.setResponse(msg);
		} else {
			log.warn("没有找到对应的RpcFutureResponse对象-requestId = " + msg.getRequestId());
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		log.error("客户端出错", cause);
		ctx.close();
	}
}
